package controller;

import dao.UserDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    UserDao userDao = new UserDao();

    //请求跳转到注册jsp页面
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //servlet接受请求，通过请求转发跳转到jsp展示对应的页面
        request.getRequestDispatcher("/register.jsp").forward(request,response);
    }


    //获取表单提交的参数信息
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //能够获取表单提交的参数信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");

        System.out.println(username+"==="+password+"==="+nickname);

        //调用userdao方法添加用户信息
        int total = 0;
        try {
            total = userDao.addUser(username,password,nickname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (total>0){
            //用户注册成功，跳转登录页面
            response.sendRedirect("/login");

        }else{
            //用户注册失败，返回失败页面
           request.setAttribute("errorMsg","注册失败");
           request.getRequestDispatcher("/error.jsp").forward(request,response);
        }

    }
}
